package com.example.webviewexample;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ViewSourceActivity extends FragmentActivity implements
        WebViewController, WebViewViewSourceInterface,
        WebViewStateChangeListener {

    private static final int SHOW_HTML_DELAY = 500;

    private TextView mWebPageTextView;
    private TextView mSourceTextView;
    private ImageView mTabLine;
    private ViewPager mViewPager;
    private FragmentPagerAdapter mPagerAdapter;
    private List<Fragment> mFragments;
    private WebPageFragment mWebPageFragment;
    private WebSourceFragment mWebSourceFragment;

    private String mUrl = null;
    private int mCurrentPageIndex = 0;
    private int mTabLineWidth = 0;

    private Controller mController = null;

    private Handler mHandler = new Handler();

    private String mHtml = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.view_source_main);

        initFromIntent();

        initView();
    }

    private void initFromIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mUrl = intent
                    .getStringExtra(WebViewExampleConstant.EXTRA_VIEW_SOURCE_URL);
        }
    }

    private void initView() {
        mWebPageTextView = (TextView) findViewById(R.id.tab_title_one);
        mSourceTextView = (TextView) findViewById(R.id.tab_title_two);
        mTabLine = (ImageView) findViewById(R.id.tabline);

        mViewPager = (ViewPager) findViewById(R.id.view_source_view_pager);

        mFragments = new ArrayList<Fragment>();
        mWebPageFragment = new WebPageFragment();
        mWebSourceFragment = new WebSourceFragment();
        mFragments.add(mWebPageFragment);
        mFragments.add(mWebSourceFragment);

        if (!TextUtils.isEmpty(mUrl)) {
            Bundle bundle = new Bundle();
            bundle.putString(WebViewExampleConstant.EXTRA_VIEW_SOURCE_URL, mUrl);
            mWebPageFragment.setArguments(bundle);
        }
        mWebPageFragment.setWebViewStateChangeListener(this);

        mPagerAdapter = new FragmentTabPagerAdapter(getSupportFragmentManager());

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOnPageChangeListener(new OnFragmentChangeListener());

        initTabLine();
    }

    private void initTabLine() {
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        int screenWidth = outMetrics.widthPixels;

        LayoutParams lp = mTabLine.getLayoutParams();
        mTabLineWidth = screenWidth >> 1;
        lp.width = mTabLineWidth;
        mTabLine.setLayoutParams(lp);
    }

    public class FragmentTabPagerAdapter extends FragmentPagerAdapter {

        public FragmentTabPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments != null ? mFragments.get(position) : null;
        }

        @Override
        public int getCount() {
            return mFragments != null ? mFragments.size() : 0;
        }
    }

    public class OnFragmentChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPx) {
            if (position < mFragments.size()) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTabLine
                        .getLayoutParams();
                if (mCurrentPageIndex <= position) {
                    lp.leftMargin = (int) (mCurrentPageIndex * mTabLineWidth + positionOffset
                            * mTabLineWidth);
                } else {
                    lp.leftMargin = (int) (mCurrentPageIndex * mTabLineWidth + (positionOffset - 1)
                            * mTabLineWidth);
                }
                mTabLine.setLayoutParams(lp);
            }
        }

        @Override
        public void onPageSelected(int position) {
            resetTextViews();

            switch (position) {
            case 0:
                mWebPageTextView.setTextColor(getResources().getColor(
                        R.color.pager_selected_text_color));
                break;
            case 1:
                mSourceTextView.setTextColor(getResources().getColor(
                        R.color.pager_selected_text_color));
                updatePageSource();
                break;
            }

            mCurrentPageIndex = position;
        }

    }

    private void resetTextViews() {
        mWebPageTextView.setTextColor(getResources().getColor(
                R.color.pager_unselected_text_color));
        mSourceTextView.setTextColor(getResources().getColor(
                R.color.pager_unselected_text_color));
    }

    private void updatePageSource() {
        mHtml = mController.getSource();

        if (mHandler != null) {
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    mWebSourceFragment.setText(mHtml);
                }
            }, SHOW_HTML_DELAY);
        }
    }

    @Override
    public void onWebViewCreate() {

    }

    @Override
    public void onWebViewControllerCreated(Controller controller) {
        mController = controller;

        mController.setObserver(ViewSourceActivity.this);
    }

    @Override
    public String getSource() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void loadUrl(String url) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageFinished(WebView view, String url) {

    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setJavaScriptInterface(JavaScriptLocalObject obj,
            String interfaceName) {
        // TODO Auto-generated method stub

    }
}
